package pers.xiqingbo.service.impl;

import pers.xiqingbo.dao.BookDao;
import pers.xiqingbo.dao.OrderDao;
import pers.xiqingbo.dao.OrderItemDao;
import pers.xiqingbo.dao.impl.BookDaoImpl;
import pers.xiqingbo.dao.impl.OrderDaoImpl;
import pers.xiqingbo.dao.impl.OrderItemDaoImpl;
import pers.xiqingbo.pojo.*;
import pers.xiqingbo.service.OrderService;

import java.util.Date;
import java.util.Map;

/**
 * @PackageName: pers.xiqingbo.service.impl
 * @ClassName: OrderServiceImpl
 * @Description: 订单管理业务逻辑层接口实现类
 * @Author: Schieber
 * @Date: 2021/3/3 下午 16:27
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    /**
     * 订单管理业务逻辑层接口
     *
     * @param cart   购物车对象
     * @param userId 用户id
     * @return 返回创建成功的订单号
     */
    @Override
    public String createOrder(Cart cart, Integer userId) {
        // 定义订单id的唯一性（采用时间戳加用户id的方式）
        String orderId = System.currentTimeMillis() + "" + userId;

        // 创建订单对象
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);

        // 调用OrderDao接口保存订单
        orderDao.saveOrder(order);

        // 遍历得到购物车每一个商品
        for (Map.Entry<Integer, CartGoods> cartGoodsMap : cart.getCartGoods().entrySet()
        ) {
            // 获取购物车每一个商品
            CartGoods cartGoods = cartGoodsMap.getValue();
            // 获取商品信息将其转换为订单项
            OrderItem orderItem = new OrderItem(null, cartGoods.getName(), cartGoods.getCount(), cartGoods.getPrice(), cartGoods.getTotalPrice(), orderId);
            // 调用OrderItemDao接口保存订单项
            orderItemDao.saveOrderItem(orderItem);

            // 通过商品id查出该商品信息
            Book book = bookDao.queryBookById(cartGoods.getId());
            // 设置该商品销量（当前销量加购物车结算时数量）
            book.setSales(book.getSales() + cartGoods.getCount());
            // 设置该商品库存（当前销量减购物车结算时数量）
            book.setStock(book.getStock() - cartGoods.getCount());
            // 更新商品信息
            bookDao.updateBook(book);
        }
        // 创建订单后清空购物车所有商品
        cart.clearCart();
        return orderId;
    }
}
